package com.ce.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ce.server.common.HscheckVo;
import com.ce.server.common.RespBean;
import com.ce.server.common.RespPageBean;
import com.ce.server.mapper.HscheckMapper;
import com.ce.server.mapper.StudentMapper;
import com.ce.server.pojo.Hscheck;
import com.ce.server.pojo.Student;
import com.ce.server.service.IHscheckService;
import com.ce.server.util.AdminUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 郑爽
 * @since 2021-11-17
 */
@Service
public class HscheckServiceImpl extends ServiceImpl<HscheckMapper, Hscheck> implements IHscheckService {

  @Autowired
  StudentMapper studentMapper;
  @Autowired
  HscheckMapper hscheckMapper;


  /**
   * 核酸人员根据核酸结果录入信息
   *
   * @param ids
   * @param hsResult
   * @return
   */
  @Override
  @Transactional
  public RespBean writeHsResultInToTable(Integer[] ids, String sno, String hsResult) {
    String jkmStatus = hsResult.equals("阴") ? "绿码" : "非绿码";
    String wno = AdminUtil.getCurrentAdmin().getUsername();
    Hscheck hscheck = new Hscheck().setWno(wno).setHsResultTime(LocalDateTime.now()).setHsResult(hsResult);
    Student student = new Student().setJkm_status(jkmStatus);
    int inputResult = hscheckMapper.update(hscheck, new LambdaUpdateWrapper<Hscheck>().in(Hscheck::getId,
            Arrays.asList(ids)));
    int updateStudentJkm = studentMapper.update(student, new LambdaUpdateWrapper<Student>().eq(Student::getSno,
            sno));

    if (inputResult > 0 && updateStudentJkm > 0) {
      if (hsResult.equals("阳")) return RespBean.success("录入成功,尽快将该学号为" + sno + "的学生进校隔离!");
      return RespBean.success("录入成功");
    }
    return RespBean.error("录入失败!");
  }

  /**
   * 分页处理获取所有的核酸记录
   *
   * @param currentPage
   * @param size
   * @param hscheck
   * @return
   */
  @Override
  public RespPageBean getHsChecksByPage(Integer currentPage, Integer size, Hscheck hscheck, LocalDate[] createTimeScope, LocalDate[] hsResultScope, String sname) {
    Page<HscheckVo> page = new Page<>(currentPage, size);
    IPage<HscheckVo> hsCheckByPage = hscheckMapper.getHsCheckByPage(page, hscheck, createTimeScope, hsResultScope,sname);
    if (hsCheckByPage != null) {
      // hsCheckByPage.getRecords().stream().map(a->a.get)
      return new RespPageBean(hsCheckByPage.getTotal(), hsCheckByPage.getRecords());
    }
    return new RespPageBean(0L, null);
  }
}
